/**
 * (created at 2011-1-19)
 */
package qiushuo.mysqlparser.ast.expression.string;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.expression.TernaryOperatorExpression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * <code>higherPreExpr 'NOT'? 'LIKE' higherPreExpr ('ESCAPE' higherPreExpr)?</code>
 * 
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class LikeExpression extends TernaryOperatorExpression {
    private final boolean not;

    /**
     * @param escape null is no ESCAPE
     */
    public LikeExpression(boolean not, Expression comparee, Expression pattern, Expression escape) {
        super(comparee, pattern, escape);
        this.not = not;
    }

    @Override
    public int getPrecedence() {
        return PRECEDENCE_COMPARISION;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            if (getFirst().getPrecedence() < getPrecedence()) {
                sb.append('(').append(getFirst().generateSql(type)).append(')');
            } else {
                sb.append(getFirst().generateSql(type));
            }
            if (not) {
                sb.append(" NOT");
            }
            sb.append(" LIKE ");
            if (getSecond().getPrecedence() < getPrecedence()) {
                sb.append('(').append(getSecond().generateSql(type)).append(')');
            } else {
                sb.append(getSecond().generateSql(type));
            }
            if (getThird() != null) {
                sb.append(" ESCAPE ");
                if (getThird().getPrecedence() < getPrecedence()) {
                    sb.append('(').append(getThird().generateSql(type)).append(')');
                } else {
                    sb.append(getThird().generateSql(type));
                }
            }
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }
}
